<template>
  <view class="chart-container">
    <!-- 图表容器 -->
    <qiun-data-charts ref="chartRef" :type="type" :chartData="chartData" :opts="chartOptions" @getIndex="handleTooltip"
      :onmovetip="true" :onzoom="true" :ontouch="true" :canvas2d="true" :canvasId="canvasId"
      @legendSelectChanged="onLegendChange" @onChartReady="onChartReady" />

    <!-- 自定义Tooltip -->
    <view v-if="showCustomTooltip" class="custom-tooltip" :style="{
        left: tooltipPosition.x + 'px',
        top: tooltipPosition.y + 'px',
        'pointer-events': 'none',
      }">
      <view class="tooltip-hed">
        <view>{{
          tooltipData.title
          }}</view>
      </view>
      <view style="min-width: 200px; border: none; margin-top: 10rpx">
        <view style="border-bottom: 1px solid #d9d9d9; width: 100%">
          <view style="padding:4rpx 0 16rpx 0;">销量</view>
          <view style="
              display: flex;
              justify-content: space-between;
              padding-bottom: 4px;
              width: 100%;
            " v-for="(item, index) in tooltipData.datas" :key="index">
            <view style="color: #666;font-weight: 400;">
              <view class="circle-icon" :style="{
                  'background-color': canvasId == 'proChart' ? produColors[item.name] : (canvasId == 'buyerChart' ? buyerColors[item.name] : item.color),
                }"></view>{{ item.name }}
            </view>
            <view>{{
              item.val
              }}</view>
          </view>
        </view>
      </view>
      <view class="tooltip-footer" v-if="type == 'mix'">
        <view>销售价格</view>
        <view>{{
          tooltipData.price
          }}</view>
      </view>
    </view>
  </view>
</template>
<script>
  import { produColors, buyerColors } from "./baseData.js";
  export default {
    props: {
      type: {
        type: String,
        default: "mix",
      },
      canvasId: {
        type: String,
        default: "",
      },
      chartData: {
        type: Object,
        default: () => { },
      },
      chartOptions: {
        type: Object,
        default: () => {
          {
          }
        },
      },
    },
    watch: {
      chartData(newVal) {
        this.showCustomTooltip = false;
      },
      showCustomTooltip(newVal) {
        if (newVal) {
          setTimeout(() => {
            this.showCustomTooltip = false;
          }, 3000);
        }
      },
    },
    created() {
      this.produColors = produColors
      this.buyerColors = buyerColors
    },
    data() {
      return {
        // Tooltip相关数据
        buyerColors: buyerColors,
        produColors: produColors,
        showCustomTooltip: false,
        tooltipPosition: { x: 0, y: 0 },
        tooltipData: {
          title: "",
          price: 0,
          datas: [],
        },
      };
    },
    methods: {
      // 图表初始化完成回调
      onChartReady(chart) {
        this.chartInstance = chart; // 保存实例
        this.scrollToRight(); // 调用滚动方法
      },
      // 手动滚动到最右侧
      scrollToRight() {
        if (!this.chartInstance) return;
        const lastIndex = this.chartData.categories.length - 1;
        this.chartInstance.scrollTo({
          xAxis: {
            index: lastIndex, // 滚动到最后一个数据点
          },
        });
      },
      onLegendChange(e) {
        console.log('图例点击事件', e.detail);
        const { index, name, show } = e.detail;
      },
      // 处理Tooltip显示
      handleTooltip(e) {
        const series = e.opts;
        const { x, y } = e.event;
        if (e.currentIndex.index === -1) {
          // 触摸离开
          this.showCustomTooltip = false;
          return;
        }

        // 准备Tooltip数据
        let titleName = e.opts.categories[e.currentIndex.index].split("-");

        this.$set(
          this.tooltipData,
          "title",
          titleName[0].length > 2
            ? titleName[0] + "年" + titleName[1] + "月" + titleName[2] + "日"
            : titleName[0] + "月" + titleName[1] + "月"
        );
        const showDatas = []
        e.opts.series.forEach(item => {
          if (item.show) {
            showDatas.push({
              name: item.name,
              color: item.color,
              val: (Math.round(item.data[e.currentIndex.index] * 100)) / 100
            })
          }
        })
        this.$set(
          this.tooltipData,
          "datas",
          this.type == "mix" ? showDatas.slice(0, -1) : showDatas
        );
        this.$set(
          this.tooltipData,
          "price",
          (Math.round(e.opts.series[e.opts.series.length - 1].data[e.currentIndex.index] * 100)) / 100
        );
        // 更新Tooltip位置
        this.tooltipPosition = {
          x: (x + 10) > 230 ? 230 : ((x + 10) < 92 ? 92 : x + 10), // 水平偏移
          y: y - 10, // 垂直偏移
        };

        this.showCustomTooltip = true;
      },

      // 如果需要点击Tooltip
      handleTooltipClick() {
        uni.showToast({
          title: `查看${this.tooltipData.title}详情`,
          icon: "none",
        });
      },
    },
  };
</script>
<style lang="less" scoped>
  /* 图表容器 */
  .chart-container {
    width: 100%;
    height: 500rpx;
    position: relative;
  }

  /* 自定义Tooltip样式 */
  .custom-tooltip {
    position: absolute;
    min-width: 200rpx;
    background: rgba(255, 255, 255, 0.85);
    border-radius: 12rpx;
    padding: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    backdrop-filter: blur(10rpx);
    z-index: 9999;
    font-size: 14px;
    font-weight: 700;
    color: #333333;
    transform: translate(-50%, -100%);
    transition: all 0.2s ease;
    min-height: 200rpx;
  }

  .circle-icon {
    display: inline-block;
    width: 22rpx;
    height: 22rpx;
    border-radius: 50%;
    margin-right: 10rpx;
  }

  .tooltip-hed {
    padding: 4px 0 4px 0;
    text-align: left;
    width: 100%;
    font-size: 16px;
    font-weight: bold;
    color: #000000;
    border-bottom: 1px solid #d9d9d9;
  }

  .tooltip-footer {
    border-top: 1rpx solid rgba(255, 255, 255, 0.1);
    padding-top: 12rpx;
    margin-top: 12rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>